package com.andy.qi.domain;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.andy.qi.conf.RoomServerConf;
import com.andy.qi.service.RoomMgr;
import com.andy.qi.util.Http;
import com.andy.qi.util.Json;
import com.fasterxml.jackson.databind.JsonNode;

@Component
public class GameServerInfo extends TimerTask {
    
    @Autowired private RoomMgr roomMgr;
    @Autowired private RoomServerConf config;

    private static Timer timer = new Timer(true);
    
    public int load;
    public String serverIp;
    private long lastTickTime = 0L;

    @PostConstruct
    private void start() {
        this.load = roomMgr.getTotalRooms();
        timer.schedule(this, 1000, 1000);
    }

    @Override
    public void run() {
        //向大厅服定时心跳
        if(lastTickTime + config.getHttpTickTime() < System.currentTimeMillis()){
            lastTickTime = System.currentTimeMillis();
            this.load = roomMgr.getTotalRooms();
            
            Map<String, String> params = new HashMap<>();
            params.put("load", String.valueOf(this.load));
            params.put("id", config.getServerId());
            params.put("clientip", config.getClientIp());
            params.put("clientport", String.valueOf(config.getClientPort()));
            params.put("httpPort", String.valueOf(config.getHttpPort()));
            
            String retStr = Http.get("http://" + config.getHallIp() + ":" + config.getHallPort() + "/register_gs", params);
            if(StringUtils.isEmpty(retStr)) {
                return;
            }
            JsonNode result = Json.toJsonNode(retStr);
            if(result.get("errcode").asInt() == 0) {
                this.serverIp = result.get("data").get("ip").asText();
            }
        }
    }

}
